package com.letoo.dragon.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.letoo.dragon.common.domain.SensitiveWordsData;
import com.letoo.dragon.common.domain.SensitiveWordsError;
import com.letoo.dragon.common.domain.SensitiveWordsResult;

/**
 * 妙喵使用的敏感词过滤工具包。提供敏感词校验方法。
 * 
 * @author dengjie
 *
 */
public class MSensitiveWordsUtils {

    private static final Logger LOG = LoggerFactory.getLogger(MSensitiveWordsUtils.class);
    /**
     * hoapi的自定义用户的token
     */
    private static final String TOKEN = "dc3c259d4b2e368ee03200c4e30a51aa";

    /**
     * hoapi的服务url
     */
    private static final String URL = "http://www.hoapi.com/index.php/Home/Api/check";

    /**
     * 敏感词过滤。
     * 
     * @param content
     *            需要被检查过滤的内容。
     * @return SensitiveWordsResult 对象。里面包含了http://www.hoapi.com/ 敏感词服务的格式。定义很清楚。
     * 
     */
    public static SensitiveWordsResult checkSensitiveWords(String content) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("str", content);
        params.put("token", TOKEN);
        SensitiveWordsResult res = null;
        try {
            long beginTime = System.currentTimeMillis();
            String json = MyHttpclientUtils.doGetAndThrowable(URL, params, 6000, 6000, null);
            long endTime = System.currentTimeMillis();
            LOG.info("MyHttpclientUtils.doGetAndThrowable use time is:" + (endTime - beginTime));
            res = JSON.parseObject(json, SensitiveWordsResult.class);
        } catch (Exception e) {
            // 如果失败走银哥的校验。
            String sensitiveWordStr = SensitiveWordUtil.filterConten(content);
            if (StringUtils.isNotBlank(sensitiveWordStr)) {
                res = new SensitiveWordsResult();
                res.setCode(1);
                res.setStatus(false);
                res.setMsg("检测到敏感字符！");
                SensitiveWordsData data = new SensitiveWordsData();
                data.setInput_str(content);
                data.setNew_str(content.replaceAll(sensitiveWordStr, "*"));
                List<SensitiveWordsError> error = new ArrayList<SensitiveWordsError>();
                SensitiveWordsError swe = new SensitiveWordsError();
                swe.setAttr("*");
                swe.setTimes(1);
                swe.setWeight(20);
                swe.setWord(sensitiveWordStr);
                error.add(swe);
                data.setError(error);
                res.setData(data);
            }
        }
        return res;
    }

    public static void main(String[] args) {
        MSensitiveWordsUtils.checkSensitiveWords("阿三地方 藏独邓杰");

    }
}
